//
//  ServerUtility.m
//  Project6
//
//  Created by ToanDK on 11/20/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//

#import "ServerUtility.h"
#import "MBProgressHUD.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"

@implementation ServerUtility

static UIViewController *rootViewController;

+(void) setRootViewController:(UIViewController *) rootCtr
{
    rootViewController = rootCtr;
}

+(void) loginWithAction:(NSString *) action Udid:(NSString*)uniqueIdentifier Api:(NSString*)api DeviceName:(NSString*) devicename UserName:(NSString *) username Password:(NSString *) password 
{
    // show indicator
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:rootViewController.view animated:YES];
    hud.labelText =@"Processing";
     // Starting request
     NSURL *url = [NSURL URLWithString:@"http://dave.appus.net.nz/account.php"];
     ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
     [request setPostValue:action forKey:@"action"];
     [request setPostValue:uniqueIdentifier forKey:@"udid"];
     [request setPostValue:api forKey:@"api"];
     [request setPostValue:devicename forKey:@"device_name"];
     [request setPostValue:username forKey:@"user"];
     [request setPostValue:password forKey:@"pass"];
    
     [request setDelegate:self];
     [request startAsynchronous];
    
}

+ (void)requestFinished:(ASIHTTPRequest *)request
{
    
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
        
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSString *responseString = [request responseString];
        NSLog(@"response string:%@",responseString);
        
        
    } else {
        NSLog(@"Unexpected error");
    }
    
    [MBProgressHUD hideHUDForView:rootViewController.view animated:YES];
}

+ (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"error:%@",error.localizedDescription);
    
    [MBProgressHUD hideHUDForView:rootViewController.view animated:YES];
}


@end
